package com.shopng.server.commands;

import java.util.Properties;

import org.apache.geode.distributed.LocatorLauncher;
import org.apache.geode.distributed.LocatorLauncher.Builder;
import org.apache.geode.distributed.LocatorLauncher.LocatorState;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;

import com.shopng.utils.ConfigHelper;
import com.shopng.utils.ConfigHelper.ITEMS;
import com.shopng.utils.LogUtil;
import com.shopng.utils.WorkPathHelper;


public class GeodLocator
{
  @Option(name = "-name", usage = "Locator name,default:node0,node1...")
  private String name;
  @Option(name = "-configXml", usage = "Locator config file")
  private String configXml = "cache.xml";
  @Option(name = "-port", usage = "Locator config file")
  private int port = -1;
  private final static int defaultPort = 12345;
  
  private static GeodLocator gl = new GeodLocator();
  
  public final static GeodLocator getInstance() {
    return gl;
  }

  private GeodLocator() {

  }

  /**
   * @param args
   */
  public static void main(String[] args) throws Exception {
    GeodLocator.getInstance().start(args);;
  }
  
  public void start(String[] args)
  {
    Properties props = ConfigHelper.getConfig("gemfire.properties");
    Builder builder = new Builder();
    props.forEach((propertyName,propertyValue)->{
      builder.set((String)propertyName, (String)propertyValue);
    });
    ConfigHelper.initConfig();
    ConfigHelper.setProperty(ITEMS.NODE_TYPE.name(), "locator");
    
    CmdLineParser cp = new CmdLineParser(this);
    try
    {
      cp.parseArgument(args);
    }
    catch (CmdLineException e)
    {
      e.printStackTrace();
    }
    if (port == -1) {
        port = defaultPort;
    }
    name = WorkPathHelper.verifyServerName(ITEMS.GS_WORK, "locator", name);
    StringBuilder buil = new StringBuilder();
    buil.append(ConfigHelper.getConfig(ITEMS.GS_WORK)).append("/").append("locator").append("/").append(name);
    ConfigHelper.setProperty(ITEMS.NODE_WORK_DIR, buil.toString());
    ConfigHelper.setProperty(ConfigHelper.ITEMS.NODE_NAME.name(), name);
    ConfigHelper.initLog4j();
    ConfigHelper.setMemberName(name);
    builder.setBindAddress(ConfigHelper.getConfig(ITEMS.BINDIP));
    builder.setPort(port);
    builder.setWorkingDirectory(buil.toString());
    builder.set("cluster-configuration-dir", buil.toString());
    builder.setMemberName("locator_"+name);
    builder.set("log-file", ConfigHelper.getConfig(ITEMS.GS_HOME)+"/log/locator-"+name+".log");
    
    ConfigHelper.initLog4j();
    
    LocatorLauncher locatorLauncher = builder.build();
    LocatorState state = locatorLauncher.start();
    System.out.println("Locator status:"+state.getStatus());
    LogUtil.getCoreLog().info("Locator status:{},msg:{}",state.getStatus(),state.getStatusMessage());
    locatorLauncher.waitOnLocator();
  }
}
